package com.yzc.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.yzc.Dto.LoginRequestDTO;
import com.yzc.mapper.UserBeanMapper;
import com.yzc.pojo.UserBean;
import com.yzc.util.JwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.MDC;
import org.slf4j.Marker;
import org.slf4j.MarkerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Slf4j
@RestController
@RequestMapping("/user")
public class LoginController {

    @Autowired
    private UserBeanMapper userBeanMapper;
    @Autowired
    private JwtUtil jwtUtil;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    private static final Marker LOG_MARKER = MarkerFactory.getMarker("LOG");

    @PostMapping("/login")
    public Map<String, Object> login(@RequestBody LoginRequestDTO requestDTO) {
        Map<String, Object> map = new HashMap<>();

        // 查询用户
        QueryWrapper<UserBean> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("name", requestDTO.getName()).eq("pass", requestDTO.getPass());
        List<UserBean> list = userBeanMapper.selectList(queryWrapper);
        if (!list.isEmpty()) {

            UserBean user = list.get(0);
            String token = jwtUtil.generateToken(user.getName());
            // 将令牌存入 Redis，设置过期时间（例如 3600 秒，即 1 小时）
            ValueOperations<String, String> valueOps = stringRedisTemplate.opsForValue();
            valueOps.set("TOKEN:" + user.getId(), token, 1, TimeUnit.HOURS);


            MDC.put("username", user.getName());
            // 记录登录成功的日志


            // 构建响应
            map.put("token", token);
            map.put("name", user.getName());
            map.put("userid", user.getId());
            map.put("result", "success");
            log.info(LOG_MARKER, "登录成功");
        } else {
            log.info(LOG_MARKER, "登录失败");
            map.put("result", "error");
        }

        return map;
    }
}
